<?php

/**
 * Description of PDOconnect
 *
 * @author aleksa
 * 
 * contact <qwertalex@yahoo.com>
 * 
 * version 1.0
 * 
 * 
 * 
 * test code
 */
class PDOconnect
{
    
    public static $dbconnect=false;
    public  $table=false;
    public $row=false;
    



/**
 * 
 * 
 * 
 * 
 * 
 * 
 * 
 * 
 * 
 */

    public function __construct() {
 #this is database connection file stored outside root (/var/ss/ss.php);
#include_once '../../ss/ss.php';#gets $user and $pass;
#------------------------------------------------------------------------
    try {
        if (! self::$dbconnect) {
             self::$dbconnect=new PDO("mysql:host=".HOST.";dbname=".DB_NAME.";charset=utf8",DB_USERNAME,DB_PASSWORD,
                 array(PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION));
        }
       
                
    } catch (Exception $e) {
        echo $e->getMessage();die();
    }
 }
    #END __consturctor()
#=============================================================================================================
 
 
 
 
 
 /**
  * 
  * @param type $query
  * @param array $options
  * @return type
  * 
  * <code>
$dbh=new PDOconnect();#connect;
$id=2;#values from spolja;
 $query=<<<h
 select mi.id_pages, mi.menu_item_location,    
p.file_location
   from menu_items as mi
       inner join pages as p
        where mi.id_pages=?  ;
        
h;

$customOptions=array(
  array("num"=>1,"value"=>$id,"options"=>"int")  
    
    
);
foreach ($dbh->custom($query, $customOptions) as $val) {
    echo $val['file_location']."<br />";
}

  * </code>
  * 
  * 
  * 
  */
public function custom($query,array $options) {
         $stmt = self::$dbconnect->prepare($query);
         foreach ($options as $key => $value) {
              $value['options']=="int"?$type=PDO::PARAM_INT: $type=PDO::PARAM_STR;
             $stmt->bindValue($value['num'], $value['value'], $type);
          }
         
      
$stmt->execute();
return $stmt;
    }
#================================================================================================    
    
    /**
     * 
     * @param type $id
     * @return type
     * @throws Exception
     * 
     * <code>
$dbh=new PDOconnect();#connect
$dbh->table="menu_items";#required database table
$dbh->rowId="id_pages";#required row
$id=2;#required id;
#$id='2 or 1=1';#sql injection wont work yeeeea

foreach ($dbh->getById($id) as $key => $value) {
    foreach ($value as $v) {
        echo $v."||";
    }
}
     * 
     * 
     * </code>
     * 
     * 
     * 
     */
public function getById($id){
    
      #table and id vars are required!================================================
      if (!$this->table) { throw new Exception('variable $table is not defined');}
      if (!$this->row) { throw new Exception('$this->rowId is not defined');}
      #===============================================================================
      
      $stmt = self::$dbconnect->prepare("SELECT * FROM $this->table WHERE $this->row=:id");
$stmt->bindValue(':id', $id, PDO::PARAM_INT);
$stmt->execute();
return $stmt;
     
  }
    
    
  
  
/**
 * get value by string 
 * manual:
 * define table #$dbh->table="menu_items";
 * define row  #$dbh->rowStr="menu_item_location";
 * define value #$str='home';
 * 
 * @param type $str
 * @return type
 * @throws Exception
 * 
 * <code>
$dbh=new PDOconnect();#connect
$dbh->table="menu_items";#required database table
$dbh->rowStr="menu_item_location";#required row
$str='home';#required search string

foreach ($dbh->getByStr($str) as $k => $va) {
    echo $va['id_pages'].'-'.$va['menu_item_text'].'-'.$va['menu_item_location'].'<br />';
    }
 * </code>
 * 
 * 
 * 
 * 
 */  
  
public function getByStr($str){
    
      #table and id vars are required!================================================
      if (!$this->table) { throw new Exception('variable $table is not defined');}
      if (!$this->row) { throw new Exception('$this->rowStr is not defined');}
      #===============================================================================
      $stmt = self::$dbconnect->prepare("SELECT * FROM $this->table WHERE $this->row=:name");

$stmt->bindValue(':name', $str, PDO::PARAM_STR);
$stmt->execute();

      
return $stmt;
      
      
  }
    
 #=========================================================================================
  

  
  
  
  
  
  
  /**
   * 
   * @return type
   * @throws Exception
   * 
   * 
   * 
   * 
   * 
   * 
   */
 public function getAll() {
  #table var are required!============================================================
      if (!$this->table) { throw new Exception('variable $table is not defined');}
  #===================================================================================
$stmt = self::$dbconnect->query("SELECT * FROM $this->table");

return $stmt;
   
 }
  
   #=========================================================================================================
 
 
 
 
 
/**
 * Ubacibanje vrednosti u bazu sa prepare stejtmentima!
 * manual:
 * treba da se definise tabela;
 * treba da se definise array sa:
    opcionalnim arrajem rows=>array(mysql rows)
    requred array "values"=>array(values);
    opcional array "type"=>array(type);
 * 
 * @param array $inserArray
 * @return type
 * @throws Exception
 * 
 * <code>
$dbh=new PDOconnect();#connect
$dbh->table="menu_items";#required database table

#values from spolja
$location="menu locaiton";
$text="menu text";
 * 
#varianta jedan sa ubacivanjem u odredjene rows
$inserArray=array(
  "rows"=>array("menu_item_location","menu_item_text")  ,
    "values"=>array($location,$text),
      "type"=>array("string","string")
);
 * 
 #varianta 2 sa ubacivanjem u sve rows (bez array rows)
$inserArray=array(
    "values"=>array(null,$location,$text),
      "type"=>array("string","string")
);

$dbh->insert($inserArray);#ubacivanje

 * 
 * </code>
 * 
 * 
 */
public function insert(array $inserArray){
    
      #table and id vars are required!================================================
      if (!$this->table) { throw new Exception('variable $table is not defined');}
      #===============================================================================
  $rows=" ";$values=" ";$i=1;
      if (array_key_exists("rows", $inserArray)) {
          $rows= "(". implode(",", $inserArray['rows']).")";
      }
      if (!array_key_exists("values", $inserArray)) {
          throw new Exception("values are required!");
      }
      foreach ($inserArray['values'] as $value) {
          $values.="?,";
          
          
      }
      
      $values=  substr_replace($values,"", -1);
      
     
  $stmt = self::$dbconnect->prepare("insert into {$this->table} {$rows}  values({$values} )");
 foreach ($inserArray['values'] as $v) {
         $v['type']=="int"?$type=PDO::PARAM_INT: $type=PDO::PARAM_STR;
          $stmt->bindValue($i, $v, $type);
          $i++;
      }

$stmt->execute();

if ($stmt->rowCount()>0) {
    return TRUE;
}
    return  false;  
     
  }
    
 #=========================================================================================
    
  
  
  
  
  
  
  
  
  
  
    
    
    
    
}


